import Vue from 'vue'
import Vuex from 'vuex'
import { info } from '@/api/login'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    username: '',
    avatarUrl: '',
    isDarkTheme: localStorage.getItem('theme') === 'dark'
  },
  getters: {
  },
  mutations: {
    setUserInfo (state, { username, avatarUrl }) {
      state.username = username
      state.avatarUrl = avatarUrl
    },
    toggleTheme (state) {
      state.isDarkTheme = !state.isDarkTheme
      const theme = state.isDarkTheme ? 'dark' : 'light'
      // 更新 localStorage
      localStorage.setItem('theme', theme)
      // 更新 html 的 data-theme 属性
      document.documentElement.setAttribute('data-theme', theme)
      // 强制重新计算样式并触发重排
      ;(() => {
        document.documentElement.style.display = 'none'
        // eslint-disable-next-line no-unused-expressions
        document.documentElement.offsetHeight
        document.documentElement.style.display = ''
      })()
    },
    initTheme (state) {
      // 初始化主题
      const theme = localStorage.getItem('theme') || 'light'
      state.isDarkTheme = theme === 'dark'
      document.documentElement.setAttribute('data-theme', theme)
      // 确保主题样式已加载
      document.documentElement.style.visibility = 'visible'
    }
  },
  actions: {
    // 获取用户信息
    async getUserInfo ({ commit }) {
      try {
        const response = await info()
        if (response.code === 1 && response.data) {
          commit('setUserInfo', {
            username: response.data.username || '用户',
            avatarUrl: response.data.img || ''
          })
        }
      } catch (error) {
        console.error('获取用户信息失败：', error)
      }
    }
  },
  modules: {
  }
})
